<template>
  <div class="media-album-view">
    <div class="album-header glass-card">
      <div class="header-top">
        <button class="back-btn" @click="goBack">
          <svg fill="none" viewBox="0 0 24 24">
            <path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2"/>
          </svg>
          返回
        </button>
        <div class="header-actions">
          <button class="action-btn edit" @click="editAlbum">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" stroke="currentColor" stroke-width="2"/>
              <path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" stroke-width="2"/>
            </svg>
            编辑
          </button>
          <div class="more-actions">
            <button class="action-btn more" @click="showMoreMenu = !showMoreMenu">
              <svg fill="none" viewBox="0 0 24 24">
                <circle cx="12" cy="12" r="1" stroke="currentColor" stroke-width="2"/>
                <circle cx="19" cy="12" r="1" stroke="currentColor" stroke-width="2"/>
                <circle cx="5" cy="12" r="1" stroke="currentColor" stroke-width="2"/>
              </svg>
            </button>
            <div v-if="showMoreMenu" class="more-menu" @click.stop>
              <button class="menu-item" @click="shareAlbum">
                <svg fill="none" viewBox="0 0 24 24">
                  <circle cx="18" cy="5" r="3" stroke="currentColor" stroke-width="2"/>
                  <circle cx="6" cy="12" r="3" stroke="currentColor" stroke-width="2"/>
                  <circle cx="18" cy="19" r="3" stroke="currentColor" stroke-width="2"/>
                  <line stroke="currentColor" stroke-width="2" x1="8.59" x2="15.42" y1="13.51" y2="17.49"/>
                  <line stroke="currentColor" stroke-width="2" x1="15.41" x2="8.59" y1="6.51" y2="10.49"/>
                </svg>
                分享相册
              </button>
              <button class="menu-item" @click="downloadAlbum">
                <svg fill="none" viewBox="0 0 24 24">
                  <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" stroke="currentColor" stroke-width="2"/>
                </svg>
                下载相册
              </button>
              <button class="menu-item danger" @click="deleteAlbum">
                <svg fill="none" viewBox="0 0 24 24">
                  <polyline points="3,6 5,6 21,6" stroke="currentColor" stroke-width="2"/>
                  <path d="M19,6v14a2,2 0 0,1 -2,2H7a2,2 0 0,1 -2,-2V6m3,0V4a2,2 0 0,1 2,-2h4a2,2 0 0,1 2,2v2" stroke="currentColor" stroke-width="2"/>
                </svg>
                删除相册
              </button>
            </div>
          </div>
        </div>
      </div>
      <div class="album-info">
        <h1 class="album-title">{{ album.name }}</h1>
        <p class="album-description">{{ album.description }}</p>
        <div class="album-meta">
          <span class="media-count">
            <svg fill="none" viewBox="0 0 24 24">
              <rect height="18" rx="2" ry="2" stroke="currentColor" stroke-width="2" width="18" x="3" y="3"/>
              <circle cx="8.5" cy="8.5" r="1.5" stroke="currentColor" stroke-width="2"/>
              <polyline points="21,15 16,10 5,21" stroke="currentColor" stroke-width="2"/>
            </svg>
            {{ album.mediaCount }} 个文件
          </span>
          <span class="album-date">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M8 2v4M16 2v4M3 10h18M5 4h14a2 2 0 012 2v14a2 2 0 01-2 2H5a2 2 0 01-2-2V6a2 2 0 012-2z" stroke="currentColor" stroke-width="2"/>
            </svg>
            {{ formatDate(album.createdAt) }}
          </span>
          <span class="album-size">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" stroke="currentColor" stroke-width="2"/>
              <polyline points="14,2 14,8 20,8" stroke="currentColor" stroke-width="2"/>
            </svg>
            {{ formatFileSize(album.totalSize) }}
          </span>
        </div>
      </div>
    </div>

    <div class="album-toolbar glass-card">
      <div class="toolbar-left">
        <div class="view-options">
          <button
            :class="{ active: viewMode === 'grid' }"
            class="view-btn"
            @click="viewMode = 'grid'"
          >
            <svg fill="none" viewBox="0 0 24 24">
              <rect height="7" stroke="currentColor" stroke-width="2" width="7" x="3" y="3"/>
              <rect height="7" stroke="currentColor" stroke-width="2" width="7" x="14" y="3"/>
              <rect height="7" stroke="currentColor" stroke-width="2" width="7" x="14" y="14"/>
              <rect height="7" stroke="currentColor" stroke-width="2" width="7" x="3" y="14"/>
            </svg>
            网格
          </button>
          <button
            :class="{ active: viewMode === 'list' }"
            class="view-btn"
            @click="viewMode = 'list'"
          >
            <svg fill="none" viewBox="0 0 24 24">
              <line stroke="currentColor" stroke-width="2" x1="8" x2="21" y1="6" y2="6"/>
              <line stroke="currentColor" stroke-width="2" x1="8" x2="21" y1="12" y2="12"/>
              <line stroke="currentColor" stroke-width="2" x1="8" x2="21" y1="18" y2="18"/>
              <line stroke="currentColor" stroke-width="2" x1="3" x2="3.01" y1="6" y2="6"/>
              <line stroke="currentColor" stroke-width="2" x1="3" x2="3.01" y1="12" y2="12"/>
              <line stroke="currentColor" stroke-width="2" x1="3" x2="3.01" y1="18" y2="18"/>
            </svg>
            列表
          </button>
        </div>

        <div class="sort-options">
          <select v-model="sortBy" class="sort-select">
            <option value="date-desc">日期降序</option>
            <option value="date-asc">日期升序</option>
            <option value="name-asc">名称 A-Z</option>
            <option value="name-desc">名称 Z-A</option>
            <option value="size-desc">大小降序</option>
            <option value="type">类型分组</option>
          </select>
        </div>
      </div>

      <div class="toolbar-right">
        <div class="search-box">
          <svg class="search-icon" fill="none" viewBox="0 0 24 24">
            <circle cx="11" cy="11" r="8" stroke="currentColor" stroke-width="2"/>
            <path d="m21 21-4.35-4.35" stroke="currentColor" stroke-width="2"/>
          </svg>
          <input
            v-model="searchQuery"
            class="search-input"
            placeholder="搜索文件..."
            type="text"
          />
        </div>

        <button class="action-btn add" @click="addMedia">
          <svg fill="none" viewBox="0 0 24 24">
            <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
            <line stroke="currentColor" stroke-width="2" x1="12" x2="12" y1="8" y2="16"/>
            <line stroke="currentColor" stroke-width="2" x1="8" x2="16" y1="12" y2="12"/>
          </svg>
          添加媒体
        </button>

        <button class="action-btn select" @click="toggleSelectMode">
          <svg fill="none" viewBox="0 0 24 24">
            <polyline points="20,6 9,17 4,12" stroke="currentColor" stroke-width="2"/>
          </svg>
          {{ selectMode ? '取消选择' : '批量选择' }}
        </button>
      </div>
    </div>

    <div class="album-content">
      <div v-if="selectMode" class="selection-bar glass-card">
        <div class="selection-info">
          <span>已选择 {{ selectedMedia.length }} 个文件</span>
          <button class="select-all-btn" @click="selectAllMedia">
            {{ selectedMedia.length === filteredMedia.length ? '取消全选' : '全选' }}
          </button>
        </div>
        <div class="selection-actions">
          <button class="batch-btn move" @click="moveSelectedMedia">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z" stroke="currentColor" stroke-width="2"/>
            </svg>
            移动到
          </button>
          <button class="batch-btn download" @click="downloadSelectedMedia">
            <svg fill="none" viewBox="0 0 24 24">
              <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" stroke="currentColor" stroke-width="2"/>
            </svg>
            下载
          </button>
          <button class="batch-btn delete" @click="deleteSelectedMedia">
            <svg fill="none" viewBox="0 0 24 24">
              <polyline points="3,6 5,6 21,6" stroke="currentColor" stroke-width="2"/>
              <path d="M19,6v14a2,2 0 0,1 -2,2H7a2,2 0 0,1 -2,-2V6m3,0V4a2,2 0 0,1 2,-2h4a2,2 0 0,1 2,2v2" stroke="currentColor" stroke-width="2"/>
            </svg>
            删除
          </button>
        </div>
      </div>

      <div :class="viewMode" class="media-container">
        <div
          v-for="media in filteredMedia"
          :key="media.id"
          :class="{ selected: selectedMedia.includes(media.id) }"
          class="media-item glass-card"
          @click="handleMediaClick(media)"
        >
          <div v-if="selectMode" class="media-checkbox">
            <input
              :checked="selectedMedia.includes(media.id)"
              type="checkbox"
              @change="toggleMediaSelection(media.id)"
              @click.stop
            />
          </div>

          <div class="media-thumbnail">
            <img v-if="media.type === 'image'" :alt="media.name" :src="media.thumbnail" />
            <video v-else-if="media.type === 'video'" :poster="media.poster" :src="media.thumbnail" muted />
            <div v-else :class="media.type" class="media-icon">
              <svg v-if="media.type === 'audio'" fill="none" viewBox="0 0 24 24">
                <path d="M9 18V5l12-2v13" stroke="currentColor" stroke-width="2"/>
                <circle cx="6" cy="18" r="3" stroke="currentColor" stroke-width="2"/>
                <circle cx="18" cy="16" r="3" stroke="currentColor" stroke-width="2"/>
              </svg>
              <svg v-else fill="none" viewBox="0 0 24 24">
                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" stroke="currentColor" stroke-width="2"/>
                <polyline points="14,2 14,8 20,8" stroke="currentColor" stroke-width="2"/>
              </svg>
            </div>

            <div class="media-overlay">
              <div v-if="media.duration" class="media-duration">
                {{ formatDuration(media.duration) }}
              </div>
              <div class="media-size">
                {{ formatFileSize(media.fileSize) }}
              </div>
            </div>
          </div>

          <div class="media-info">
            <h3 class="media-title">{{ media.name }}</h3>
            <div class="media-details">
              <span class="media-date">{{ formatDate(media.date) }}</span>
              <span class="media-type">{{ getMediaTypeText(media.type) }}</span>
              <span v-if="media.tags" class="media-tags">
                {{ media.tags.slice(0, 2).join(', ') }}
                <span v-if="media.tags.length > 2">+{{ media.tags.length - 2 }}</span>
              </span>
            </div>
          </div>

          <div class="media-actions">
            <button class="quick-action" title="快速预览" @click.stop="quickPreview(media)">
              <svg fill="none" viewBox="0 0 24 24">
                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" stroke="currentColor" stroke-width="2"/>
                <circle cx="12" cy="12" r="3" stroke="currentColor" stroke-width="2"/>
              </svg>
            </button>
            <button class="quick-action" title="收藏" @click.stop="toggleFavorite(media)">
              <svg fill="none" viewBox="0 0 24 24">
                <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" stroke="currentColor" stroke-width="2"/>
              </svg>
            </button>
          </div>
        </div>
      </div>

      <div v-if="filteredMedia.length === 0" class="empty-state">
        <div class="empty-icon">
          <svg fill="none" viewBox="0 0 24 24">
            <rect height="18" rx="2" ry="2" stroke="currentColor" stroke-width="2" width="18" x="3" y="3"/>
            <circle cx="8.5" cy="8.5" r="1.5" stroke="currentColor" stroke-width="2"/>
            <polyline points="21,15 16,10 5,21" stroke="currentColor" stroke-width="2"/>
          </svg>
        </div>
        <h3>暂无媒体文件</h3>
        <p>此相册中还没有任何媒体文件</p>
        <button class="btn btn-primary" @click="addMedia">
          <svg fill="none" viewBox="0 0 24 24">
            <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
            <line stroke="currentColor" stroke-width="2" x1="12" x2="12" y1="8" y2="16"/>
            <line stroke="currentColor" stroke-width="2" x1="8" x2="16" y1="12" y2="12"/>
          </svg>
          添加媒体文件
        </button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

interface Album {
  id: string
  name: string
  description: string
  mediaCount: number
  createdAt: Date
  totalSize: number
  coverImage?: string
}

interface MediaFile {
  id: string
  name: string
  type: 'image' | 'video' | 'audio' | 'document'
  thumbnail?: string
  poster?: string
  date: Date
  fileSize: number
  duration?: number
  tags?: string[]
  favorite: boolean
}

const route = useRoute()
const router = useRouter()

const album = ref<Album>({
  id: '',
  name: '',
  description: '',
  mediaCount: 0,
  createdAt: new Date(),
  totalSize: 0
})

const albumMedia = ref<MediaFile[]>([])
const showMoreMenu = ref(false)
const selectMode = ref(false)
const selectedMedia = ref<string[]>([])
const viewMode = ref<'grid' | 'list'>('grid')
const sortBy = ref('date-desc')
const searchQuery = ref('')

onMounted(() => {
  loadAlbum()
})

const loadAlbum = () => {
  const albumId = route.params.id as string

  album.value = {
    id: albumId,
    name: '家庭旅行',
    description: '2024年春节家庭旅行精彩回忆，记录了与家人共度的美好时光',
    mediaCount: 24,
    createdAt: new Date('2024-02-10'),
    totalSize: 2.8 * 1024 * 1024 * 1024, // 2.8GB
    coverImage: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600&fit=crop'
  }

  albumMedia.value = [
    {
      id: '1',
      name: '海边日落.jpg',
      type: 'image',
      thumbnail: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=300&fit=crop',
      date: new Date('2024-02-10T18:30:00'),
      fileSize: 3.2 * 1024 * 1024,
      tags: ['日落', '海边', '风景', '旅行'],
      favorite: true
    },
    {
      id: '2',
      name: '沙滩嬉戏.mp4',
      type: 'video',
      thumbnail: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=400&h=300&fit=crop',
      poster: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=800&h=600&fit=crop',
      date: new Date('2024-02-11T10:15:00'),
      fileSize: 45.6 * 1024 * 1024,
      duration: 180,
      tags: ['沙滩', '孩子', '游戏', '欢乐'],
      favorite: false
    },
    {
      id: '3',
      name: '度假音乐.mp3',
      type: 'audio',
      date: new Date('2024-02-11T15:20:00'),
      fileSize: 8.1 * 1024 * 1024,
      duration: 240,
      tags: ['音乐', '轻松', '度假'],
      favorite: false
    },
    {
      id: '4',
      name: '海滩自拍.jpg',
      type: 'image',
      thumbnail: 'https://images.unsplash.com/photo-1551632811-561732d1e306?w=400&h=300&fit=crop',
      date: new Date('2024-02-12T14:45:00'),
      fileSize: 2.8 * 1024 * 1024,
      tags: ['自拍', '家庭', '海滩', '笑容'],
      favorite: true
    }
  ]
}

const goBack = () => {
  router.back()
}

const getMediaIcon = (type: string) => {
  switch (type) {
    case 'video': return '🎥'
    case 'audio': return '🎵'
    case 'document': return '📄'
    default: return '📁'
  }
}

const getMediaTypeText = (type: string) => {
  switch (type) {
    case 'image': return '图片'
    case 'video': return '视频'
    case 'audio': return '音频'
    case 'document': return '文档'
    default: return '文件'
  }
}

const formatDate = (date: Date) => {
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (days === 0) return '今天'
  if (days === 1) return '昨天'
  if (days < 7) return `${days} 天前`

  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDuration = (seconds: number): string => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 计算属性
const filteredMedia = computed(() => {
  let filtered = albumMedia.value

  // 搜索过滤
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(media =>
      media.name.toLowerCase().includes(query) ||
      media.tags?.some(tag => tag.toLowerCase().includes(query))
    )
  }

  // 排序
  switch (sortBy.value) {
    case 'date-desc':
      return filtered.sort((a, b) => b.date.getTime() - a.date.getTime())
    case 'date-asc':
      return filtered.sort((a, b) => a.date.getTime() - b.date.getTime())
    case 'name-asc':
      return filtered.sort((a, b) => a.name.localeCompare(b.name))
    case 'name-desc':
      return filtered.sort((a, b) => b.name.localeCompare(a.name))
    case 'size-desc':
      return filtered.sort((a, b) => b.fileSize - a.fileSize)
    case 'type':
      return filtered.sort((a, b) => a.type.localeCompare(b.type))
    default:
      return filtered
  }
})

// 事件处理
const editAlbum = () => {
  showMoreMenu.value = false
  console.log('编辑相册')
}

const shareAlbum = () => {
  showMoreMenu.value = false
  console.log('分享相册')
}

const downloadAlbum = () => {
  showMoreMenu.value = false
  console.log('下载相册')
}

const deleteAlbum = () => {
  showMoreMenu.value = false
  if (confirm('确定要删除这个相册吗？此操作无法撤销。')) {
    console.log('删除相册')
    router.push('/media')
  }
}

const addMedia = () => {
  router.push('/media/upload')
}

const toggleSelectMode = () => {
  selectMode.value = !selectMode.value
  if (!selectMode.value) {
    selectedMedia.value = []
  }
}

const toggleMediaSelection = (mediaId: string) => {
  const index = selectedMedia.value.indexOf(mediaId)
  if (index > -1) {
    selectedMedia.value.splice(index, 1)
  } else {
    selectedMedia.value.push(mediaId)
  }
}

const selectAllMedia = () => {
  if (selectedMedia.value.length === filteredMedia.value.length) {
    selectedMedia.value = []
  } else {
    selectedMedia.value = filteredMedia.value.map(media => media.id)
  }
}

const handleMediaClick = (media: MediaFile) => {
  if (selectMode.value) {
    toggleMediaSelection(media.id)
  } else {
    openMedia(media)
  }
}

const openMedia = (media: MediaFile) => {
  router.push(`/media/${media.id}`)
}

const quickPreview = (media: MediaFile) => {
  console.log('快速预览:', media.name)
}

const toggleFavorite = (media: MediaFile) => {
  media.favorite = !media.favorite
  console.log('收藏状态:', media.favorite)
}

const moveSelectedMedia = () => {
  console.log('移动选中的媒体:', selectedMedia.value)
}

const downloadSelectedMedia = () => {
  console.log('下载选中的媒体:', selectedMedia.value)
}

const deleteSelectedMedia = () => {
  if (confirm(`确定要删除选中的 ${selectedMedia.value.length} 个文件吗？`)) {
    console.log('删除选中的媒体:', selectedMedia.value)
    selectedMedia.value = []
  }
}
</script>

<style lang="scss" scoped>
.media-album-view {
  padding: $spacing-6;
  max-width: 1200px;
  margin: 0 auto;
}

.album-header {
  padding: $spacing-6;
  margin-bottom: $spacing-6;

  .back-btn {
    background: rgba(255, 255, 255, 0.5);
    border: 1px solid rgba($gray-300, 0.5);
    border-radius: $radius-md;
    padding: $spacing-2 $spacing-3;
    margin-bottom: $spacing-4;
    cursor: pointer;
    font-size: $font-size-sm;

    &:hover {
      background: rgba(255, 255, 255, 0.7);
    }
  }

  .album-info {
    .album-title {
      font-size: $font-size-3xl;
      font-weight: $font-weight-bold;
      color: $gray-800;
      margin-bottom: $spacing-2;
    }

    .album-description {
      color: $gray-600;
      font-size: $font-size-base;
      margin-bottom: $spacing-2;
    }

    .media-count {
      color: $gray-500;
      font-size: $font-size-sm;
    }
  }
}

.album-content {
  .media-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: $spacing-4;
  }

  .media-item {
    padding: $spacing-3;
    cursor: pointer;
    transition: all $duration-normal ease;

    &:hover {
      transform: translateY(-2px);
    }

    .media-thumbnail {
      width: 100%;
      height: 140px;
      border-radius: $radius-md;
      overflow: hidden;
      margin-bottom: $spacing-2;
      background: $gray-100;
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .media-icon {
        font-size: $font-size-3xl;
      }
    }

    .media-info {
      h3 {
        font-size: $font-size-sm;
        font-weight: $font-weight-medium;
        color: $gray-800;
        margin-bottom: $spacing-1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .media-date {
        color: $gray-500;
        font-size: $font-size-xs;
      }
    }
  }
}

.empty-state {
  text-align: center;
  padding: $spacing-12;
  color: $gray-500;
}

@media (max-width: $breakpoint-sm) {
  .media-album-view {
    padding: $spacing-4;
  }

  .media-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: $spacing-3;
  }
}
</style>
